#region (c) 2014 THN Solutions LLC. - All rights reserved
/*
Simplified BSD License (BSD)
Copyright (c) 2014, THN Solutions LLC. ( www.ThnSolutions.com )
Author: Nguyễn, M. Hải                 ( www.Minh-Hai.com     )
All rights reserved.

Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this 
      list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above copyright notice, 
      this list of conditions and the following disclaimer in the documentation 
      and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 
IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
POSSIBILITY OF SUCH DAMAGE.
*/
#endregion

#region Record of Change
//             							CHANGE HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | DEVELOPER  | DESCRIPTION                                              |
// -------------------------------------------------------------------------------------
// | 05-Nov-09 | HaiNM      | First creation.                                          |
// -------------------------------------------------------------------------------------
//
#endregion

#region Record of Audit
//             							REVIEW HISTORY
// -------------------------------------------------------------------------------------
// |   DATE    | REVIEWER   | NOTES                                                    |
// -------------------------------------------------------------------------------------
// -------------------------------------------------------------------------------------
//
#endregion

#region Using directives
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;

using Thn;
#endregion

namespace Thn.Drawing
{
    /// <summary>
    /// Helper class for various graphics methods.
    /// </summary>
#if DEBUG
    public
#else
    public
#endif
    class GraphicUtils
    {
        #region Fields
        private static ColorMatrix grayMatrix = new ColorMatrix();
        private static ImageAttributes grayAttributes = new ImageAttributes();
        #endregion

        #region DrawText
        /// <summary>
        /// render text, default alignment is MiddleLeft
        /// </summary>
        public static void DrawText(System.Drawing.Graphics canvas, string text, Font font, Color color, Rectangle aRect)
        {
            DrawText(canvas, text, font, color, aRect.Left, aRect.Top, aRect.Right, aRect.Bottom, ContentAlignment.MiddleLeft);
        }

        /// <summary>
        /// render text
        /// </summary>
        public static void DrawText(System.Drawing.Graphics canvas, string text, Font font, Color color, Rectangle aRect, ContentAlignment align)
        {
            DrawText(canvas, text, font, color, aRect.Left, aRect.Top, aRect.Right, aRect.Bottom, align);
        }

        public static void DrawText(System.Drawing.Graphics canvas, string text, Font font, Color color, int x1, int y1, int x2, int y2, ContentAlignment align)
        {
            DrawText(canvas, text, font, new SolidBrush(color), x1, y1, x2, y2, align);
        }

        public static void DrawText(System.Drawing.Graphics canvas, string text, Font font, Brush brush, int x1, int y1, int x2, int y2, ContentAlignment align)
        {
            float x = 0;
            float y = 0;
            SizeF ts;
            ts = canvas.MeasureString(text, font);
            //find x
            switch (align)
            {
                case ContentAlignment.TopLeft:
                    x = x1;
                    y = y1;
                    break;
                case ContentAlignment.TopRight:
                    x = x2 - ts.Width;
                    y = y1;
                    break;
                case ContentAlignment.TopCenter:
                    x = ((x1 + x2) - ts.Width) / 2;
                    y = y1;
                    break;
                case ContentAlignment.MiddleLeft:
                    x = x1;
                    y = ((y1 + y2) - ts.Height) / 2;
                    break;
                case ContentAlignment.MiddleRight:
                    x = x2 - ts.Width;
                    y = ((y1 + y2) - ts.Height) / 2;
                    break;
                case ContentAlignment.MiddleCenter:
                    x = ((x1 + x2) - ts.Width) / 2;
                    y = ((y1 + y2) - ts.Height) / 2;
                    break;
                case ContentAlignment.BottomLeft:
                    x = x1;
                    y = y2 - ts.Height;
                    break;
                case ContentAlignment.BottomRight:
                    x = x2 - ts.Width;
                    y = y2 - ts.Height;
                    break;
                case ContentAlignment.BottomCenter:
                    x = ((x1 + x2) - ts.Width) / 2;
                    y = y2 - ts.Height;
                    break;
            }
            canvas.DrawString(text, font, brush, x, y);
        }

        #endregion

        #region Draw Gradient
        public static void DrawGradient(System.Drawing.Graphics canvas, Rectangle rect, Color StartColor, Color EndColor, System.Drawing.Drawing2D.LinearGradientMode mode)
        {
            canvas.FillRectangle(new System.Drawing.Drawing2D.LinearGradientBrush(rect, StartColor, EndColor, mode), rect);
        }
        #endregion

        #region Draw Triangle
        public static void DrawTriangle(System.Drawing.Graphics g, Rectangle r, bool Up, Color c)
        {
            Point[] p = new Point[3];

            if (Up)
            {
                p[0].X = r.Left; p[0].Y = r.Top + r.Height;
                p[1].X = r.Left + r.Width / 2; p[1].Y = r.Top;
                p[2].X = r.Left + r.Width; p[2].Y = r.Top + r.Height;
            }
            else
            {
                p[0].X = r.Left; p[0].Y = r.Top;
                p[1].X = r.Left + r.Width / 2; p[1].Y = r.Top + r.Height;
                p[2].X = r.Left + r.Width; p[2].Y = r.Top;
            }

            g.FillPolygon(new SolidBrush(c), p);
        }

        public static void DrawTriangle(System.Drawing.Graphics g, RectangleF r, int angle, Color c)
        {

            Matrix myMatrix = new Matrix(1, 0, 0, 1, 0, 0);
            g.Transform = myMatrix;
            g.TranslateTransform(r.Left + r.Width / 2, r.Top + r.Height / 2, MatrixOrder.Append);

            GraphicsPath myGraphicsPath = new GraphicsPath();

            PointF[] p = new PointF[3];
            p[0].X = -r.Width / 2; p[0].Y = 0;
            p[1].X = r.Width / 2; p[1].Y = -r.Height / 2;
            p[2].X = r.Width / 2; p[2].Y = r.Height / 2;

            myGraphicsPath.AddLines(p);

            Matrix myPathMatrix = new Matrix();
            myPathMatrix.Rotate(angle, MatrixOrder.Append);
            myGraphicsPath.Transform(myPathMatrix);

            g.FillPath(new SolidBrush(c), myGraphicsPath);

            g.ResetTransform();
        }

        public static void DrawTriangle(System.Drawing.Graphics g, Rectangle r, int angle, Color c)
        {
            RectangleF rec = new RectangleF(r.Location, r.Size);
            DrawTriangle(g, rec, angle, c);
        }
        #endregion

        #region Get the desired Rounded Rectangle path.
        /// <summary>
        /// Create a rounded rectangle path
        /// </summary>
        public static GraphicsPath MakeRoundedRectangle(Rectangle r, CurveStyles styles, int radius)
        {
            bool topLeft = (styles & CurveStyles.TopLeft) == CurveStyles.TopLeft;
            bool topRight = (styles & CurveStyles.TopRight) == CurveStyles.TopRight;
            bool bottomLeft = (styles & CurveStyles.BottomLeft) == CurveStyles.BottomLeft;
            bool bottomRight = (styles & CurveStyles.BottomRight) == CurveStyles.BottomRight;

            return MakeRoundedRectangle(r, topLeft, topRight, bottomLeft, bottomRight, radius);
        }

        /// <summary>
        /// Create a rounded rectangle path
        /// </summary>
        public static GraphicsPath MakeRoundedRectangle(Rectangle r, bool topLeft, bool topRight, bool bottomLeft, bool bottomRight, int radius)
        {
            GraphicsPath result = new GraphicsPath();

            #region Old codes
            //top left
            //result.AddArc(r.Left, r.Top, radius * 2, radius * 2, 180, 90);

            //top
            //result.AddLine(r.Left + radius, r.Top, r.Left + r.Width - (radius * 2), r.Top);            

            //top right
            //result.AddArc(r.Left + r.Width - (radius * 2), r.Top, radius * 2, radius * 2, 270, 90);

            //right
            //result.AddLine(r.Left + r.Width, r.Top + radius, r.Left + r.Width, r.Top + r.Height - (radius * 2));

            //bottom right
            //result.AddArc(r.Left + r.Width - (radius * 2), r.Top + r.Height - (radius * 2), radius * 2, radius * 2, 0, 90);

            //bottom
            //result.AddLine(r.Left + r.Width - (radius * 2), r.Top + r.Height, r.Left + radius, r.Top + r.Height);

            //bottom left
            //result.AddArc(r.Left, r.Top + r.Height - (radius * 2), radius * 2, radius * 2, 90, 90);

            //left
            //result.AddLine(r.Left, r.Top + r.Height - (radius * 2), r.Left, r.Top + radius);
            #endregion


            if (bottomRight)
            {
                result.AddArc(r.Right - radius - 1, r.Bottom - radius - 1, radius + 1, radius + 1, 0, 90);
            }
            else
            {
                Point p = new Point(r.Right, r.Bottom);
                result.AddLine(p, p);
            }

            if (bottomLeft) result.AddArc(r.Left, r.Bottom - radius, radius, radius, 90, 90);
            else
            {
                Point p = new Point(r.Left, r.Bottom);
                result.AddLine(p, p);
            }

            if (topLeft) result.AddArc(r.Left, r.Top, radius, radius, 180, 90);
            else
            {
                Point p = new Point(r.Left, r.Top);
                result.AddLine(p, p);
            }

            if (topRight) result.AddArc(r.Right - radius, r.Top, radius, radius, 270, 90);
            else
            {
                Point p = new Point(r.Right, r.Top);
                result.AddLine(p, p);
            }

            result.CloseFigure();

            return result;
        }

        /// <summary>
        /// Create a rounded rectangle path
        /// </summary>
        public static GraphicsPath MakeTopRoundedTab(Rectangle r, int radius, bool closeFigure)
        {
            GraphicsPath result = new GraphicsPath();

            //left
            //result.AddLine(r.Left, r.Top + r.Height - (radius * 1), r.Left, r.Top + radius);
            result.AddLine(r.Left, r.Bottom, r.Left, r.Top + radius);

            //top left
            result.AddArc(r.Left, r.Top, radius * 2, radius * 2, 180, 90);

            //top
            //result.AddLine(r.Left + radius, r.Top, r.Left + r.Width - (radius * 2), r.Top);            

            //top right
            result.AddArc(r.Left + r.Width - (radius * 2), r.Top, radius * 2, radius * 2, 270, 90);

            //right
            //result.AddLine(r.Left + r.Width, r.Top + radius, r.Left + r.Width, r.Top + r.Height - (radius * 1));
            result.AddLine(r.Right, r.Top + radius, r.Right, r.Bottom);

            //bottom
            if (closeFigure)
            {
                result.AddLine(r.Left + r.Width - (radius * 2), r.Top + r.Height, r.Left + radius, r.Top + r.Height);  
            }
            #region Defensive tracing
            else
            {
                //closure is not necessary.
            }
            #endregion

            //bottom right
            //result.AddArc(r.Left + r.Width - (radius * 2), r.Top + r.Height - (radius * 2), radius * 2, radius * 2, 0, 90);

            //bottom left
            //result.AddArc(r.Left, r.Top + r.Height - (radius * 2), radius * 2, radius * 2, 90, 90);            

            return result;
        }

        /*
        public static System.Drawing.Drawing2D.GraphicsPath MakeRoundedRectanglePath(RectangleF baseRect, float radius, bool RoundedTop, bool RoundedBottom, bool IncludeBottom)
        {
            return new GraphicsPath();
            // if corner radius is less than or equal to zero, 
            // return the original rectangle 
            if (radius <= 0.0F)
            {
                GraphicsPath mPath = new GraphicsPath();
                mPath.AddRectangle(baseRect);
                mPath.CloseFigure();
                return mPath;
            }

            // if the corner radius is greater than or equal to 
            // half the width, or height (whichever is shorter) 
            // then return a capsule instead of a lozenge 
            if ((radius >= (Math.Min(baseRect.Width, baseRect.Height)) / 2.0) && RoundedBottom)
                return MakeCapsulePath(baseRect);

            // create the arc for the rectangle sides and declare 
            // a graphics path object for the drawing 
            float diameter = radius * 2.0F;
            SizeF sizeF = new SizeF(diameter, diameter);
            RectangleF arc = new RectangleF(baseRect.Location, sizeF);
            GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();

            // top left arc 
            path.AddArc(arc, 180, 90);

            // top right arc 
            arc.X = baseRect.Right - diameter;
            path.AddArc(arc, 270, 90);


            if (IncludeBottom)
            {
                if (RoundedBottom)
                {
                    // bottom right arc 
                    arc.Y = baseRect.Bottom - diameter;
                    path.AddArc(arc, 0, 90);

                    // bottom left arc
                    arc.X = baseRect.Left;
                    path.AddArc(arc, 90, 90);
                }
                else
                {
                    path.AddLine(baseRect.Right, baseRect.Bottom, baseRect.Left, baseRect.Bottom);
                }
            }

            path.CloseFigure();
            return path;
        }
        */
        #endregion

        #region Gets the desired Capsular path.
        public static System.Drawing.Drawing2D.GraphicsPath MakeCapsulePath(RectangleF baseRect)
        {
            float diameter;
            RectangleF arc;
            GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();
            try
            {
                if (baseRect.Width > baseRect.Height)
                {
                    // return horizontal capsule 
                    diameter = baseRect.Height;
                    SizeF sizeF = new SizeF(diameter, diameter);
                    arc = new RectangleF(baseRect.Location, sizeF);
                    path.AddArc(arc, 90, 180);
                    arc.X = baseRect.Right - diameter;
                    path.AddArc(arc, 270, 180);
                }
                else if (baseRect.Width < baseRect.Height)
                {
                    // return vertical capsule 
                    diameter = baseRect.Width;
                    SizeF sizeF = new SizeF(diameter, diameter);
                    arc = new RectangleF(baseRect.Location, sizeF);
                    path.AddArc(arc, 180, 180);
                    arc.Y = baseRect.Bottom - diameter;
                    path.AddArc(arc, 0, 180);
                }
                else
                {
                    // return circle 
                    path.AddEllipse(baseRect);
                }
            }
            catch
            {
                path.AddEllipse(baseRect);
            }
            finally
            {
                path.CloseFigure();
            }
            return path;
        }
        #endregion

        #region Draw Gray Image
        public static void DrawGrayImage(System.Drawing.Graphics g, Image img, Rectangle desc)
        {
            grayMatrix.Matrix00 = 1 / 3.4f;
            grayMatrix.Matrix01 = 1 / 3.4f;
            grayMatrix.Matrix02 = 1 / 3.4f;
            grayMatrix.Matrix10 = 1 / 3.4f;
            grayMatrix.Matrix11 = 1 / 3.4f;
            grayMatrix.Matrix12 = 1 / 3.4f;
            grayMatrix.Matrix20 = 1 / 3.4f;
            grayMatrix.Matrix21 = 1 / 3.4f;
            grayMatrix.Matrix22 = 1 / 3.4f;

            grayAttributes.SetColorMatrix(grayMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            GraphicsUnit graphicsUnit = GraphicsUnit.Pixel;
            RectangleF srcRectF = img.GetBounds(ref graphicsUnit);
            g.DrawImage(img, desc, (int)srcRectF.Left, (int)srcRectF.Top,
                            (int)srcRectF.Width, (int)srcRectF.Height, graphicsUnit, grayAttributes);
        }

        public static void DrawGrayImage(System.Drawing.Graphics g, Image img, Rectangle desc, float factor)
        {
            grayMatrix.Matrix00 = factor;
            grayMatrix.Matrix01 = factor;
            grayMatrix.Matrix02 = factor;
            grayMatrix.Matrix10 = factor;
            grayMatrix.Matrix11 = factor;
            grayMatrix.Matrix12 = factor;
            grayMatrix.Matrix20 = factor;
            grayMatrix.Matrix21 = factor;
            grayMatrix.Matrix22 = factor;

            grayAttributes.SetColorMatrix(grayMatrix, ColorMatrixFlag.Default, ColorAdjustType.Bitmap);

            GraphicsUnit graphicsUnit = GraphicsUnit.Pixel;
            RectangleF srcRectF = img.GetBounds(ref graphicsUnit);
            g.DrawImage(img, desc, (int)srcRectF.Left, (int)srcRectF.Top,
                            (int)srcRectF.Width, (int)srcRectF.Height, graphicsUnit, grayAttributes);
        }

        private static void DrawImage(System.Drawing.Graphics g, Image img, Rectangle desc)
        {
            GraphicsUnit graphicsUnit = GraphicsUnit.Pixel;
            RectangleF srcRectF = img.GetBounds(ref graphicsUnit);
            g.DrawImage(img, desc, (int)srcRectF.Left, (int)srcRectF.Top,
                       (int)srcRectF.Width, (int)srcRectF.Height, graphicsUnit);

        }

        public static void DrawImage(System.Drawing.Graphics g, Image img, Rectangle desc, bool gray)
        {
            if (gray)
                DrawGrayImage(g, img, desc);
            else
                DrawImage(g, img, desc);
        }

        public static void DrawIcon(System.Drawing.Graphics g, Image img, Rectangle ControlRectangle, ContentAlignment align, bool gray)
        {
            Rectangle desc = new Rectangle();
            desc.Width = img.Width;
            desc.Height = img.Height;

            switch (align)
            {
                case ContentAlignment.TopLeft:
                    desc.X = 0;
                    desc.Y = 0;
                    break;

                case ContentAlignment.TopCenter:
                    desc.X = (ControlRectangle.Width - desc.Width) / 2;
                    desc.Y = 0;
                    break;

                case ContentAlignment.TopRight:
                    desc.X = ControlRectangle.Width - desc.Width;
                    desc.Y = 0;
                    break;

                case ContentAlignment.MiddleLeft:
                    desc.X = 0;
                    desc.Y = (ControlRectangle.Height - desc.Height) / 2;
                    break;

                case ContentAlignment.MiddleCenter:
                    desc.X = (ControlRectangle.Width - desc.Width) / 2;
                    desc.Y = (ControlRectangle.Height - desc.Height) / 2;
                    break;

                case ContentAlignment.MiddleRight:
                    desc.X = ControlRectangle.Width;
                    desc.Y = (ControlRectangle.Height - desc.Height) / 2;
                    break;

                case ContentAlignment.BottomLeft:
                    desc.X = 0;
                    desc.Y = ControlRectangle.Height - desc.Height; ;
                    break;

                case ContentAlignment.BottomCenter:
                    desc.X = (ControlRectangle.Width - desc.Width) / 2;
                    desc.Y = ControlRectangle.Height - desc.Height;
                    break;

                case ContentAlignment.BottomRight:
                    desc.X = ControlRectangle.Width - desc.Width;
                    desc.Y = ControlRectangle.Height - desc.Height;
                    break;
            }

            if (gray)
                GraphicUtils.DrawImage(g, img, desc, true);
            else
                GraphicUtils.DrawImage(g, img, desc, false);

        }
        #endregion

        #region Rotation
        /// <summary>
        /// Rotate point P with Origin and Angle
        /// </summary>
        /// <param name="Origin">Coordinate origin</param>
        /// <param name="p">Point to rotate</param>
        /// <param name="Angle">Rotate angle</param>
        public static Point RotatePoint(Point Origin, Point p, double Angle)
        {
            double dy = p.Y - Origin.Y;
            double dx = p.X - Origin.X;
            double h = Math.Sqrt(dy * dy + dx * dx);
            double inrads = Angle / 180 * Math.PI;
            return new Point((int)(Origin.X + h * Math.Cos(inrads)), (int)(Origin.Y - h * Math.Sin(inrads)));
        }

        /// <summary>
        /// Get a point location with distance from Origin is Length, and rotation Angle
        /// </summary>
        /// <param name="Origin">Origin of the coordinate system</param>
        /// <param name="Length">Distance from Origin</param>
        /// <param name="Angle">Rotation</param>
        public static Point RotatePoint(Point Origin, double Length, double Angle)
        {
            double h = Length;
            double inrads = Angle / 180 * Math.PI;
            return new Point((int)(Origin.X + h * Math.Cos(inrads)), (int)(Origin.Y - h * Math.Sin(inrads)));
        }

        #endregion

        #region Gradient Drawing
        public static void DrawGradientPath(System.Drawing.Graphics canvas, GraphicsPath path, Color StartColor, Color EndColor, bool DrawBorder, Color BorderColor, LinearGradientMode mode)
        {
            RectangleF bounds = path.GetBounds();
            //get around a bug in GDI
            bounds.Inflate(1, 1);
            Brush b = new LinearGradientBrush(bounds, StartColor, EndColor, mode);
            canvas.FillPath(b, path);
            if (DrawBorder) canvas.DrawPath(new Pen(BorderColor), path);
        }
        #endregion

        #region Constructors
        /// <summary>
        /// Default constructor.
        /// </summary>
        private GraphicUtils()
        { }
        #endregion
    }

    [Flags]
    public enum CurveStyles
    {
        /// <summary>
        /// Curve top left border
        /// </summary>
        TopLeft,

        /// <summary>
        /// Curve top right border
        /// </summary>
        TopRight,

        /// <summary>
        /// Curve bottom left border
        /// </summary>
        BottomLeft,

        /// <summary>
        /// Curve bottom right border
        /// </summary>
        BottomRight
    }
}
